//
//  RegViewController.m
//  WeiMo
//
//  Created by weixian he on 12-9-7.
//  Copyright (c) 2012年 . All rights reserved.
//

#import "RegViewController.h"

#import <QuartzCore/QuartzCore.h>

#import "UIGlossyButton.h"
#import "KeyValueObject.h"
#import "UIUnderlinedButton.h"
#import "ConferViewController.h"
#import "InterfaceDefine.h"
#import "JSONKit.h"
#import "FMManager.h"
#import "DLog.h"

#define kTextFieldTagBase 100
#define kButtonTagBase 1000
#define kFootViewHeight (200.0)

#define kNormalTitle (@"选择分类(必选)")

@interface RegViewController ()
{
    UITextField *mCurTextField;
    MBProgressHUD *mHUD;
}


/*
 keyDispName   显示的名字
 valueDispName 输入的数据
 */
@property(nonatomic,retain) NSMutableArray *textFieldDataList;  //KeyValueObject
@property(nonatomic,retain) NSMutableArray *textFieldList;      //<UITextField>


/*
 isCheck
 keyDispName 显示名字
 */
@property(nonatomic,retain) NSMutableArray *chooseDataList;     //<KeyValueObject>


@property(nonatomic,retain) UIView *footerView;
@property(nonatomic,retain) UIView *footerView2;
@end

@implementation RegViewController
@synthesize footerView,footerView2;
@synthesize textFieldDataList,textFieldList;
@synthesize chooseDataList;
@synthesize delegate;

- (void)dealloc
{
    self.delegate = nil;
    self.footerView = nil;
    self.footerView2 = nil;
    self.textFieldDataList = nil;
    self.textFieldList = nil;
    self.chooseDataList = nil;
    [super dealloc];
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[UIBarButtonItem appearance] setTintColor:[UIColor blackColor]];
    
    mHUD = nil;
    
    self.textFieldDataList = [[[NSMutableArray alloc] init] autorelease];
    {
        KeyValueObject *item = [[KeyValueObject alloc] init];
        item.keyDispName = @"用户账号:";
        [self.textFieldDataList addObject:item];
        [item release];
    }
    
    {
        KeyValueObject *item = [[KeyValueObject alloc] init];
        item.keyDispName = @"登录密码:";
        [self.textFieldDataList addObject:item];
        [item release];
    }
    {
        KeyValueObject *item = [[KeyValueObject alloc] init];
        item.keyDispName = @"确认密码:";
        [self.textFieldDataList addObject:item];
        [item release];
    }
    
    self.textFieldList = [[[NSMutableArray alloc] init] autorelease];
    CGRect rect = CGRectMake(0, 14, 190, 28);
    {
        UITextField *textField = [[UITextField alloc] initWithFrame:rect];
        textField.delegate = self;
        textField.tag = kTextFieldTagBase;
        textField.placeholder=@"不能少于6位";
        textField.clearButtonMode = UITextFieldViewModeWhileEditing; //编辑时会出现个修改X 
        textField.returnKeyType = UIReturnKeyNext;
        textField.autocorrectionType = UITextAutocorrectionTypeNo; 
        [self.textFieldList addObject:textField];
        [textField release];
    }
    {
        UITextField *textField = [[UITextField alloc] initWithFrame:rect];
        textField.delegate = self;
        textField.tag = kTextFieldTagBase + 1;
        textField.placeholder=@"不能少于6位";
        //textField.secureTextEntry = YES; //密码
        textField.clearButtonMode = UITextFieldViewModeWhileEditing; //编辑时会出现个修改X
        textField.returnKeyType = UIReturnKeyNext;
        textField.autocorrectionType = UITextAutocorrectionTypeNo; 
        [self.textFieldList addObject:textField];
        [textField release];
    }
    {
        UITextField *textField = [[UITextField alloc] initWithFrame:rect];
        textField.delegate = self;
        textField.tag = kTextFieldTagBase +2;
        textField.placeholder=@"不能少于6位";
        //textField.secureTextEntry = YES; //密码
        textField.clearButtonMode = UITextFieldViewModeWhileEditing; //编辑时会出现个修改X 
        textField.returnKeyType = UIReturnKeyDone;
        textField.autocorrectionType = UITextAutocorrectionTypeNo;  
        [self.textFieldList addObject:textField];
        [textField release];
    }

    /*
    
    CGRect subR = CGRectMake(0, 0, 320, kFootViewHeight);
    {
        self.footerView = [[[UIView alloc] initWithFrame:subR] autorelease];
        
        subR = CGRectMake(10, 40, 150, 44);
        UIButton *categoryChoose = [UIButton buttonWithType:UIButtonTypeCustom];
        categoryChoose.frame = subR;
        categoryChoose.tag = 909;
        categoryChoose.layer.masksToBounds = YES;
        categoryChoose.layer.cornerRadius = 8.0;
        categoryChoose.layer.borderColor = [UIColor colorWithWhite:0.0 alpha:0.3].CGColor;
        categoryChoose.layer.borderWidth = 1.0;
        categoryChoose.backgroundColor = [UIColor whiteColor];
        [categoryChoose setTitle:kNormalTitle forState:UIControlStateNormal];
        [categoryChoose setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [categoryChoose addTarget:self action:@selector(goToChooseCategory) forControlEvents:UIControlEventTouchUpInside];
        [self.footerView addSubview:categoryChoose];
        
        subR.origin.x = subR.origin.x + subR.size.width + 20;
        subR.size.width = 130;
        UIGlossyButton *registerWeiMo = [UIGlossyButton buttonWithType:UIButtonTypeCustom];
        registerWeiMo.frame = subR;
        [registerWeiMo useWhiteLabel:YES];
        registerWeiMo.buttonCornerRadius = 8.0;
        registerWeiMo.tintColor = [UIColor lightGrayColor];
        [registerWeiMo setTitle:@"注册" forState:UIControlStateNormal];
        [registerWeiMo setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [registerWeiMo addTarget:self action:@selector(goToRegisterWeiMo) forControlEvents:UIControlEventTouchUpInside];
        [self.footerView addSubview:registerWeiMo];
        
        subR.origin.x = (self.view.frame.size.width - 200) / 2.0;
        subR.origin.y = subR.origin.y + subR.size.height + 50;
        subR.size.width = 200;
        UIUnderlinedButton *conferBtn = [UIUnderlinedButton underlinedButton];
        conferBtn.frame = subR;
        [conferBtn setTitle:@"注册即同意WEIMO用户协议" forState:UIControlStateNormal];
        [conferBtn addTarget:self action:@selector(conferBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        conferBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [self.footerView addSubview:conferBtn];
    }
     */
    
    //用户类型  1.模特 2.演艺 3.经纪人 4.企业
    self.chooseDataList = [[[NSMutableArray alloc] init] autorelease];
    {
        KeyValueObject *item = [[[KeyValueObject alloc] init] autorelease];
        item.isCheck = YES;
        item.keyDispName = @"模特";
        [self.chooseDataList addObject:item];
        
    }
    {
        KeyValueObject *item = [[[KeyValueObject alloc] init] autorelease];
        item.keyDispName = @"企业";
        [self.chooseDataList addObject:item];
    }
    {
        KeyValueObject *item = [[[KeyValueObject alloc] init] autorelease];
        item.keyDispName = @"经纪人";
        [self.chooseDataList addObject:item];
    }
    {
        KeyValueObject *item = [[[KeyValueObject alloc] init] autorelease];
        item.keyDispName = @"演艺";
        [self.chooseDataList addObject:item];
    }
    
  
    
    CGRect footerRect = CGRectMake(0, 0, 320, 60);
    self.footerView = [[[UIView alloc] initWithFrame:footerRect] autorelease];
    //self.footerView.backgroundColor = [UIColor redColor];
    int buttonW = 80;
    int buttonSpace = 10;
    for(int i = 0; i < 3; i++)
    {
        int x = buttonSpace * (i + 1)  + i *buttonW;
        CGRect recountRect = CGRectMake(x, 5, 80, 28);
        UIButton *reCount = [UIButton buttonWithType:UIButtonTypeCustom];
        reCount.tag = kButtonTagBase + i;
        [reCount setFrame:recountRect];
        KeyValueObject *item = [self.chooseDataList objectAtIndex:i];
        NSString *title = [NSString stringWithFormat:@"  %@",item.keyDispName];
        UIImage *image;
        if(item.isCheck)
        {
            image = [UIImage imageNamed:@"check.png"];
        }
        else {
            image = [UIImage imageNamed:@"uncheck.png"];
        }
        [reCount setImage:image forState:UIControlStateNormal];
        [reCount setTitle:title forState:UIControlStateNormal];
        [reCount.titleLabel setFont:[UIFont boldSystemFontOfSize:16]];
        [reCount setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [reCount addTarget:self action:@selector(chooseBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.footerView addSubview:reCount];
    }
    
    for(int i = 0; i < 1; i++)
    {
         /*
        int x;
       
        if(i == 0)
        {
            x= buttonSpace * (i + 2)  + i *buttonW - 2;
        }
        else {
            x= buttonSpace * (i + 2)  + i *buttonW - 10;
        }
        */
        int x = buttonSpace * (i + 1)  + i *buttonW;
        
        
        CGRect recountRect = CGRectMake(x, 5 + 28 + 5, 80, 28);
        
        UIButton *reCount = [UIButton buttonWithType:UIButtonTypeCustom];
        reCount.tag = kButtonTagBase + i + 3;
        [reCount setFrame:recountRect];
        KeyValueObject *item = [self.chooseDataList objectAtIndex:(i+3)];
        NSString *title = [NSString stringWithFormat:@"  %@",item.keyDispName];
        UIImage *image;
        if(item.isCheck)
        {
            image = [UIImage imageNamed:@"check.png"];
        }
        else {
            image = [UIImage imageNamed:@"uncheck.png"];
        }
        [reCount setImage:image forState:UIControlStateNormal];
        [reCount setTitle:title forState:UIControlStateNormal];
        [reCount.titleLabel setFont:[UIFont boldSystemFontOfSize:16]];
        [reCount setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [reCount addTarget:self action:@selector(chooseBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.footerView addSubview:reCount];
    }
    
    self.footerView2 = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 60)] autorelease];
    //self.footer2View.backgroundColor = [UIColor redColor];
    
    buttonW = 200;
    float buttonx = (320 - buttonW)/2;
    UIUnderlinedButton *conferBtn = [UIUnderlinedButton underlinedButton];
    conferBtn.frame = CGRectMake(buttonx, 25, buttonW, 30);
    [conferBtn setTitle:@"注册即同意VMOKU用户协议" forState:UIControlStateNormal];
    [conferBtn addTarget:self action:@selector(conferBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    //[conferBtn setTitleColor:[UIColor colorWithWhite:0.8 alpha:1.0] forState:UIControlStateNormal];
    conferBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [self.footerView2 addSubview:conferBtn];
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

#pragma mark - Table view data source



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0)
    {
        return self.textFieldDataList.count;
    }
    else
    {
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
    {
        static NSString *registerCellIdentifier = @"registerCellIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:registerCellIdentifier];
        if(cell == nil)
        {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:registerCellIdentifier] autorelease];
            cell.textLabel.textColor = [UIColor grayColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        KeyValueObject *item = [self.textFieldDataList objectAtIndex:indexPath.row];
        cell.textLabel.textAlignment = UITextAlignmentRight;
        cell.textLabel.text = item.keyDispName;
        cell.accessoryView = [self.textFieldList objectAtIndex:indexPath.row];
        return cell;
    }
    else
    {
        static NSString *CellIdentifier2 = @"Cell2";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
        if(cell == nil)
        {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2] autorelease];
        }
        
        cell.textLabel.text = @"注册";
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.textLabel.textColor = [UIColor grayColor];
        return cell;
    }
}

#pragma mark - Table view delegate

-(float)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 25;
}

-(float)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if(section == 0)
    {
        return 80;
    }
    else {
        return 60;
    }
}

-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
    {
        return 48;
    }
    
    return 44;
    
}

-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if(section == 0)
    {
        return self.footerView;
    }
    else if(section == 1)
    {
        return self.footerView2;
    }
    return nil;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 2;
}



#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
    {
        UITextField * textField = [self.textFieldList objectAtIndex:indexPath.row];
        [textField becomeFirstResponder];
    }
    else {
        [self goToRegisterWeiMo];
    }
    
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
}


#pragma mark - UITextFieldDelegate

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    int index = textField.tag - kTextFieldTagBase;
    if(index != 2)
    {
        int i = index +1;
        UITextField *tField = [self.textFieldList objectAtIndex:i];
        [tField becomeFirstResponder];
    }
    else
    {
        [textField resignFirstResponder];
    }
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField;
{
    mCurTextField  = textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self saveCurTextField:textField];
}

#pragma mark - private

- (void)saveCurTextField:(UITextField *)textField
{
    if(textField)
    {
        int index = textField.tag - kTextFieldTagBase;
        KeyValueObject *item = [self.textFieldDataList objectAtIndex:index];
        item.valueDispName = textField.text;
    }
}

-(void)conferBtnClick:(id)sender
{
    ConferViewController *conferCtrl = [[ConferViewController alloc] init];
    [self.navigationController pushViewController:conferCtrl animated:YES];
    [conferCtrl release];
}

-(void)showAlertView:(NSString *)message
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil,nil];
    [alertView show];
    [alertView release];
}

//选择分类
- (void)goToChooseCategory
{
    RegisterKindsChooseViewController *reTypeChooseCtrl = [[[RegisterKindsChooseViewController alloc] init] autorelease];
    reTypeChooseCtrl.delegate = self;
    [self.navigationController pushViewController:reTypeChooseCtrl animated:YES];
}

//注册
-(void)goToRegisterWeiMo
{
    for(int i = 0; i< self.textFieldDataList.count; i++)
    {
        KeyValueObject *item = [self.textFieldDataList objectAtIndex:i];
        UITextField *textField = [self.textFieldList objectAtIndex:i];
        item.valueDispName = textField.text;
        if(item.valueDispName== nil || [item.valueDispName isEqualToString:@""])
        {
            NSString *message =[NSString stringWithFormat:@"%@不能为空!",item.keyDispName];
            [self showAlertView:message];
            return;
        }
        else if(item.valueDispName.length < 6)
        {
            NSString *message =[NSString stringWithFormat:@"%@ 不能少于6位!",item.keyDispName];
            [self showAlertView:message];
            return;
        }
    }

    KeyValueObject *pwd1 = [self.textFieldDataList objectAtIndex:1];
    KeyValueObject *pwd2 = [self.textFieldDataList objectAtIndex:2];
    if(![pwd1.valueDispName isEqualToString:pwd2.valueDispName])
    {
        [self showAlertView:@"密码不一致！"];
        return;
    }
    
    if(mCurTextField)
    {
        [mCurTextField resignFirstResponder];
    }
    
    
    mHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    [self.navigationController.view addSubview:mHUD];
    mHUD.delegate = self;
    [mHUD show:YES];
    
    NSString* userType = @"1";
    
    //用户类型  1.模特 2.演艺 3.经纪人 4.企业
    int i=0;
    for (; i < self.chooseDataList.count; i++) {
        KeyValueObject *item  = [self.chooseDataList objectAtIndex:i];
        if(item.isCheck)
        {
            break;
        }
    }
    
    if(i==0)//模特
    {
        userType=@"1";
    }
    else if(i == 1)//企业
    {
        userType=@"4";
    }
    else if(i == 2)//经纪人
    {
        userType=@"3";
    }
    else if(i==3)//演艺
    {
        userType=@"2";
    }

    
    NSString *urlStr =[NSString stringWithFormat:@"%@/%@",kHttpHost,kUserRegister];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    KeyValueObject *item = [self.textFieldDataList objectAtIndex:0];
    [dic setObject:item.valueDispName forKey:@"userAccountid"];
    [dic setObject:userType forKey:@"userType"];
    item = [self.textFieldDataList objectAtIndex:1];
    [dic setObject:item.valueDispName forKey:@"userPassword"];
    NSString *postStr = [dic JSONString];
    [dic release];
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:urlStr]];
    [request appendPostData:[postStr dataUsingEncoding:NSUTF8StringEncoding]];
    [request setRequestMethod:@"POST"];
    request.delegate = self;
    [request startAsynchronous];
}

-(void)chooseBtnClick:(id)sender
{
    UIButton *button = (UIButton *)sender;
    int indexTag = button.tag;
    for(KeyValueObject *item in self.chooseDataList)
    {
        item.isCheck = NO;
    }
    UIImage *imageCheck = [UIImage imageNamed:@"check.png"];
    UIImage *imageUncheck = [UIImage imageNamed:@"uncheck.png"];
    for(int i = 0; i< 5; i++)
    {
        int tag = i + kButtonTagBase;
        UIButton *btn = (UIButton *)[self.footerView viewWithTag:tag];
        if(tag == indexTag)
        {
            [btn setImage:imageCheck forState:UIControlStateNormal];
        }
        else {
            [btn setImage:imageUncheck forState:UIControlStateNormal];
        }
    }
    KeyValueObject *item = [self.chooseDataList objectAtIndex:(indexTag - kButtonTagBase)];
    item.isCheck = YES;
}

#pragma mark - RegisterKindsChooseViewControllerDelegate

- (void)returnChoosedRegisterIdentifier:(NSString *)identify
{
    NSString *title = kNormalTitle;
    if (identify.length > 0)
    {
        NSRange range = [identify rangeOfString:@","];
        if (range.location != NSNotFound)
        {
            NSArray *array = [identify componentsSeparatedByString:@","];
            title = [array objectAtIndex:0];
        }
    }
    
    UIButton *button = (UIButton *)[self.view viewWithTag:909];
    [button setTitle:title forState:UIControlStateNormal];
}

#pragma mark - ASIHTTPRequestDelegate

- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSString *urlStr = [NSString stringWithFormat:@"%@",request.url];
    NSString *action = @"";
    if (urlStr.length > 0)
    {
        NSArray *array = [urlStr componentsSeparatedByString:@"/"];
        action = [array objectAtIndex:(array.count - 1)];
    }
    DLog(@"%@",action);
    
    NSData *data = [request responseData];
    NSArray *array = [data objectFromJSONData];
    
    if(array == nil || array.count == 0)
    {
        return;
    }
    
    NSString *item0 = [array objectAtIndex:0];
    DLog(@"res = %@",item0);
    if([item0 isEqualToString:kResponseOk])
    {
        if(mHUD == nil)
        {
            mHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
            [self.navigationController.view addSubview:mHUD];
            mHUD.delegate = self;
            [mHUD show:YES];
        }
        mHUD.mode =MBProgressHUDModeText;
        mHUD.labelText = @"注册成功";
        [mHUD hide:YES afterDelay:1];
        return;
    }
    else if([item0 isEqualToString:kResponseOk2])
    {
        if(mHUD)
        {
            mHUD.hidden = YES;
        }
        UITextField *textField = [self.textFieldList objectAtIndex:0];
        NSString *name = textField.text;
        textField.text = @"";
        [self.tableView reloadData];
        
        NSString *msg = [NSString stringWithFormat:@"%@，已经注册",name];
        NSString *title = @"注册失败";
        [FMManager showAlertViewTitle:title message:msg];
        
        return;
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    if(mHUD == nil)
    {
        mHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
        [self.navigationController.view addSubview:mHUD];
        mHUD.delegate = self;
        [mHUD show:YES];
    }
    mHUD.mode =MBProgressHUDModeText;
    mHUD.labelText = @"网络链接失败";
    [mHUD hide:YES afterDelay:1.5];
}

#pragma mark -
#pragma mark MBProgressHUDDelegate methods

- (void)hudWasHidden:(MBProgressHUD *)hud {
	// Remove HUD from screen when the HUD was hidded
    if([mHUD.labelText isEqualToString:@"注册成功"])
    {
        if(self.delegate)
        {
            UITextField *textField = [self.textFieldList objectAtIndex:0];
            NSString *name = textField.text;
            [self.delegate hadReg:name];
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
	[mHUD removeFromSuperview];
	[mHUD release];
	mHUD = nil;
}

@end